package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.manager.TaskConfig;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class TaskResult extends GeneralTestWidget {

	private WlanManager wlanManager;

    private LinearLayout httptaskLayout;
    private LinearLayout ftptaskLayout;
    private LinearLayout aptaskLayout;
    private LinearLayout pingtaskLayout;
    private LinearLayout webauthtaskLayout;
    private LinearLayout peaptaskLayout;
    private LinearLayout simtaskLayout;
    private LinearLayout segregatetaskLayout;
    private LinearLayout roamtaskLayout;
    private LinearLayout snrtaskLayout;
    private LinearLayout rssitaskLayout;

    private LinearLayout httptaskTitleLayout;
    private LinearLayout aptaskTitleLayout;
    private LinearLayout webauthtaskTitleLayout;
    private LinearLayout peaptaskTitleLayout;
    private LinearLayout simtaskTitleLayout;
    private LinearLayout segregatetaskTitlteLayout;
    private LinearLayout rsnrtaskTitleLayout;
    private LinearLayout roamtaskTitleLayout;
    private String cameraFlag= "";
    private boolean isShow = false;

//	private ActivityBroadcastReceiver myReceiver;
    private Activity ctx;
    private Task task;
    private Button backBtn;
    private Button btnDraw;
    private LinearLayout taskNumLayout;
    private Handler handler;
    private String fileName;
    private Button btnPic;
    private Thread thread;
	private boolean connected = false;
	private boolean connected2 = false;
//    private Button uploadButton;
    public TaskResult(Activity context) {
        super(context);
        inflate(context, R.layout.task_result_widget, this);
        this.ctx = context;
        wlanManager = new WlanManager(ctx);
        httptaskLayout = (LinearLayout) this.findViewById(R.id.httpTaskFinishLayout);
        ftptaskLayout = (LinearLayout) this.findViewById(R.id.ftpTaskFinishLayout);
        aptaskLayout = (LinearLayout) this.findViewById(R.id.apTaskFinishLayout);
        pingtaskLayout = (LinearLayout) this.findViewById(R.id.pingTaskFinishLayout);
        webauthtaskLayout = (LinearLayout) this.findViewById(R.id.webauthTaskFinishLayout);
        peaptaskLayout = (LinearLayout) this.findViewById(R.id.peapTaskFinishLayout);
        simtaskLayout = (LinearLayout) this.findViewById(R.id.simTaskFinishLayout);
        segregatetaskLayout = (LinearLayout) this.findViewById(R.id.segregateTaskFinishLayout);
        roamtaskLayout = (LinearLayout) this.findViewById(R.id.roamTaskFinishLayout);
        snrtaskLayout = (LinearLayout) this.findViewById(R.id.snrTaskFinishLayout);
        rssitaskLayout = (LinearLayout) this.findViewById(R.id.rssiTaskFinishLayout);

        httptaskTitleLayout = (LinearLayout) this.findViewById(R.id.httpTaskLayoutTitle);
        aptaskTitleLayout = (LinearLayout) this.findViewById(R.id.apTaskLayoutTitle);
        webauthtaskTitleLayout = (LinearLayout) this.findViewById(R.id.webauthTaskLayoutTitle);
        peaptaskTitleLayout = (LinearLayout) this.findViewById(R.id.peapTaskLayoutTitle);
        simtaskTitleLayout = (LinearLayout) this.findViewById(R.id.simTaskLayoutTitle);
        segregatetaskTitlteLayout = (LinearLayout) this.findViewById(R.id.segregateTaskLayoutTitle);
        rsnrtaskTitleLayout = (LinearLayout) this.findViewById(R.id.snrTaskLayoutTitle);
        roamtaskTitleLayout = (LinearLayout) this.findViewById(R.id.roamTaskLayoutTitle);


        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK); 
        cameraFlag =(String)ctx.getIntent().getSerializableExtra(TAG_CAMERA_FLAG); 
        ctx.getIntent().putExtra(TAG_CAMERA_TASK, task);
        SharedPreferences settings = ctx.getSharedPreferences(MyMobileCfgWidget.PREFS_NAME, 0);
        String tel = settings.getString(MyMobileCfgWidget.PREFS_KEY, "");
        task.testPhone = tel;
        initTask(task,ctx,task.selNetType);
        task = dealWebAndPeapData(task);
        boolean tempResult = false;
        if(task.selNetType == ConnectivityManager.TYPE_WIFI)
        {
        	   for(int i=0;i<task.testedAp.size();i++){
               	if (task.scanResult !=null &&task.scanResult.BSSID!=null &&task.testedAp.get(i).equals(task.scanResult.BSSID)) {
               		tempResult = true;
       			}
               }
               if(! tempResult)
               	task.testedAp.add(task.scanResult.BSSID);
        }
        tempResult = false; 
        int tempNum = 0;
        for(int i=0;i< GlobalApp.taskTestList.size();i++){
        	if ( GlobalApp.taskTestList.get(i).id == task.id) {
        		tempResult = true;
        		break;
			}
        	tempNum ++;
        } 
        if(! tempResult)
        	GlobalApp.taskTestList.add(task);
        else  
        	GlobalApp.taskTestList.set(tempNum, task); 
        
        taskNumLayout = (LinearLayout) this.findViewById(R.id.taskNumLayout);
        backBtn = (Button) this.findViewById(R.id.task_result_btnBack);
        btnDraw = (Button) this.findViewById(R.id.btn_draw);
        btnPic = (Button)this.findViewById(R.id.btnpic);
        
        if (GlobalApp.DEBUG) {
			System.out.println("taskresult 测试类型" + GlobalApp.getTestType());
		}
        if (GlobalApp.getTestType() != 1) {
			btnPic.setVisibility(View.VISIBLE);
		}else {
			btnPic.setVisibility(View.GONE);
		}
        
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	String from = ctx.getIntent().getStringExtra("from");
            	from = from == null?"":from;
            	if(from.equals("TestWidget")) {
            		 ctx.setContentView(new SelectNetType_main(ctx));
            	} else {
            		backToTask(ctx);
            	}
            }
        });
        btnPic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	GlobalApp.who_to_CameraWidget = MessageWhat.TaskResult;
                CameraWidget cw = new CameraWidget(ctx);
               try {
            	   ctx.setContentView(cw);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("CameraShow", e.getMessage());
				}
            }
        });
        btnDraw.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != fileName) {
                    showMessage(ctx, "正在重新上传中...");
                    new Thread() {
                        public void run() {
                           if (uplod(fileName, ctx, handler))
                                {
                        	   		fileName = null;
                                }
                        	System.out.println("======================暂时不上传");
                        }
                    }.start();
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
               //  shotScreen();
            }   
        });
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.WIFI_SUCESS_CONNECTED:  
					dismissMessageDialog();
                	upload();
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    showMessage(ctx, "无法获取FTP账号");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                	if(cameraFlag != null && cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) {
                		System.out.println("--------------  说好的拍照呢 ？ 上传成功 。 。 。  ---------------");
                		
                	} else {
                		showMessage(ctx, "上传成功.");
	                    int value = ctx.getIntent().getIntExtra(MessageWhat.INDEX_TASK_RESULT, 0);
	            		if (value == 1) {
	            			if (GlobalApp.getTestType()!=1) {
								showCameraDialog(ctx);
							}
//	            			showCameraDialog(ctx);
	            		}
                	}
            			
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    showMessage(ctx, "上传失败");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    showMessage(ctx, "FTP登录失败");
                    break;
                }
            }
        }; 
        wlanManager.setHandler(handler); 
        show();
        if(cameraFlag == null || !cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) 
        	connectNetWork();  
    }

    private void connectNetWork(){
		   showMessageDialog(ctx, "正在连接网络..."); 
		   thread = new Thread() { 
		        @Override
		        public void run() {
			        	 if(wlanManager.checkNetworkType() != 1 && wlanManager.checkNetworkType() != 3){
			        		 if (!connected) { 
				                    connected = true;
				                    if(task.selNetType == ConnectivityManager.TYPE_WIFI){
					                    	 System.err.println("=====================1");
					                    	 wlanManager.openWifi();
							                 wlanManager.connect(task.scanResult);
				                    }else {
				                    	System.err.println("=====================2");
				                    	wlanManager.setMobileDataEnabled(true);
									}  
				                } 
			        	 }
		        	    while (!connected2) {
		        	    	 if(wlanManager.checkNetworkType() == 3 || wlanManager.checkNetworkType() == 1){
			                    	System.err.println("=====================3");
				                	connected2 = true;
				                	wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
				                }
						} 
		            }  
		        };

	    	thread.start(); 
	    }
  
    private void upload() {
    	if(task.scanResult != null && task.scanResult.SSID.equals(WlanManager.SSID_CMCC)){
			WebAuthManager wManager = new WebAuthManager(ctx);
			String  defaultUrl = ctx.getResources().getString(R.string.default_url);
	        DBManager db = new DBManager(ctx);
			Account config = db.getAccount();
			String userName ="",pwd="";
			if(null != config){ 
				userName = config.userName;
				pwd = config.password; 
//				String USER[]=AccountConfigWidget.stringAnalytical(config.userName);
//				String PWD[]=AccountConfigWidget.stringAnalytical(config.password);
//				userName = USER[0];
//					pwd = PWD[0];
			}
			wManager.auth(defaultUrl, userName, pwd);
		 	db.release();
		}
    	if(cameraFlag == null || !cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) {
    		createResultXML();
    	} else if(cameraFlag.equals(TAG_CAMERA_FLAG_VALUE)) {
    		
    		final String jpg_name =(String)ctx.getIntent().getSerializableExtra("jpg_name"); 
    		if (null != jpg_name) {
                showMessage(ctx, "正在上传截屏...");
                new Thread() {
                    public void run() {
                        uploadPic(jpg_name, ctx, handler);
                    }
                }.start();
            }
    		System.out.println("--------------  说好的拍照呢 ？ " + jpg_name + " ---------------");
    	}
    		
    }

    private void createResultXML() {
        task.endTime = StringUtils.getDateTime();
        TaskParser parser = new PullTaskParser();
        if(task.selNetType == ConnectivityManager.TYPE_WIFI){
        	fileName=parser.CreateWLANxml(task,ctx);
        }else if(task.selNetType ==ConnectivityManager.TYPE_MOBILE){
        	fileName=parser.CreateGSMxml(task,ctx);
        }else if(task.selNetType ==ConnectivityManager.TYPE_MOBILE_MMS){
        	fileName=parser.CreateTDxml(task,ctx);
        }else {
			
		}
        
    //    fileName = parser.XmlFileCreator(task);
        ctx.getIntent().putExtra("xml", fileName);
        DBManager db = new DBManager(ctx);
        db.saveTask(task.mac, task.apName, String.valueOf(task.id));
        db.release();
        if (null != fileName) {
            showMessage(ctx, "正在上传测试结果...");
            new Thread() {
                public void run() {
                    if (uplod(fileName, ctx, handler))
                        fileName = null;
                }
            }.start();
        }
        ctx.getIntent().removeExtra(TAG_REFER_TASK);
    }
   private void show() {
	    int size = 0;  
        float speed = 0,avgSuccess=0,delay = 0,avgDelay =0,avgSpeed = 0;
        DecimalFormat df = new DecimalFormat("#0.000");
        TextView t = new TextView(ctx);
        StringBuffer s = new StringBuffer();  
    	//HTTP测试 （任务测试中的巡检测试没有）
    	/*if(!task.id.equals("") && task.taskType.equals("巡检测试")) {
    		
    	} else {*/
    		httptaskTitleLayout.setVisibility(VISIBLE);
            List<HttpTask> httpTasks = task.httpTasks;
            size = httpTasks.size();
           
            int failedTimes = 0;
            for (HttpTask task : httpTasks) {
                delay += StringUtils.parseFloat(task.delay);
                speed += StringUtils.parseFloat(task.speed);
                failedTimes += task.failedTimes;
            }
            avgDelay = (float) delay / size;
            avgSpeed = (float) speed / size;
            avgSuccess = ((float) (size * task.testCount - failedTimes) / (size * task.testCount)) * 100;
            // ((float)(num*task.testCount - failedTimes)/(num*task.testCount))*100;

            s.append("平均时延：").append(df.format(avgDelay)).append(" s").append('\n');
            s.append("访问成功率：").append(avgSuccess).append(" %");
            t.setTextColor(Color.WHITE);
            t.setText(s);
            httptaskLayout.addView(t);
//    	}  
    	

      //FTP测试   (都有)
        List<FTPTask> ftpTasks = task.ftpTasks;
        size = ftpTasks.size();
        long loginTime = 0;
        float dwrate = 0, upRate = 0;
        for (FTPTask task : ftpTasks) {
            loginTime += task.loginTime;
            dwrate += StringUtils.parseFloat(task.downRate);
            upRate += StringUtils.parseFloat(task.upRate);
        }
        float avgUpRate =  size==0?0:(float) upRate / size;
        float avgDwRate =  size==0?0:(float) dwrate / size;
        float avgLoginTime =  size==0?0:(float) ((float) (loginTime / 1000) / size);
        float upSuccessNum = 0;
        float dwSuccessNum = 0;
        if(avgUpRate>0)
        	upSuccessNum = 100;
        if (avgDwRate>0) 
        	dwSuccessNum = 100;
        s = new StringBuffer();
        s.append("平均上传速度：").append(df.format(avgUpRate * 8)).append(" Kb/s").append('\n');
        s.append("平均下载速度：").append(df.format(avgDwRate * 8)).append(" Kb/s").append('\n');
        s.append("上传成功率：").append(df.format(upSuccessNum)).append(" %").append('\n');
        s.append("下载成功率：").append(df.format(dwSuccessNum)).append(" %");
        // s.append("平均登录时延：").append(df.format(avgLoginTime)).append(" s;");
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        ftptaskLayout.addView(t);
        
      //AP 关联测试 （WLAN 有）
        if(task.selNetType == ConnectivityManager.TYPE_WIFI) {
        	aptaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            s.append("平均关联时间：").append(task.relevanceAPAvgTime).append("s").append('\n');
            s.append("关联成功率：").append(task.relevanceAPSuccessRate).append("%");
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            aptaskLayout.addView(t);
        }

      //PING 测试   (都有)
        float time = 0, ttl = 0, bytes = 0;
        List<PingTask> pingTasks = task.pingTasks;
        size = ftpTasks.size();
        for (PingTask task : pingTasks) {
            time += StringUtils.parseFloat(task.time);
            ttl += StringUtils.parseFloat(task.ttl);
            bytes += StringUtils.parseFloat(task.bytes);
        }
        float avgTime =  size==0?0:(float) time / size;
        float avgTTL = size==0?0: (float) ttl / size;
        float avgBytes =  size==0?0:(float) bytes / size;
        s = new StringBuffer();
        s.append("平均时延：").append(df.format((float) avgTime / 1000)).append(" s").append('\n');
        s.append("丢包率：").append("0").append(" %");
        // s.append("Bytes：").append(df.format(avgBytes)).append(" byte;");
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        pingtaskLayout.addView(t);

      //WEB 关联测试 （WLAN 有）
        if(task.selNetType == ConnectivityManager.TYPE_WIFI) {
        	webauthtaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            if(task!=null && task.scanResult!=null && task.scanResult.SSID!=null && task.scanResult.SSID.equals(WlanManager.SSID_CMCC)){
            	   s.append("平均认证时间：").append(task.webDelay).append("s").append('\n');
                   s.append("认证成功率：").append(task.webSuccessRate).append("%").append('\n');
                   s.append("下线成功率：").append(task.webOffSuccessRate).append("%");
            }else {
            	 s.append("当前wifi网络类型不支持Web认证\n");
			}
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            webauthtaskLayout.addView(t);
        } 
        if(task.id.equals("") && task.selNetType == ConnectivityManager.TYPE_WIFI) {
        	isShow = true;
        } else if(!task.id.equals("") && task.selNetType == ConnectivityManager.TYPE_WIFI
        		&& task.taskType.equals("验收测试")) {
        	isShow = true;
        }
        System.err.println(task.taskType+":"+task.selNetType+":"+task.testFlag);
        if(isShow) {
        	
        	//PEAP 测试 （一键测试WLAN、验收测试WLAN）
        	peaptaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            if(task!=null && task.scanResult!=null && task.scanResult.SSID!=null && task.scanResult.SSID.equals(WlanManager.SSID_CMCC_AUTO)){
            	   s.append("认证成功率：").append(task.peapSuccessRate).append("%");
                   s.append("\n下线成功率：").append(task.peapOffSuccessRate).append("%");
            }else {
            	   s.append("当前wifi网络类型不支持Peap认证\n");
			}
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            peaptaskLayout.addView(t);
            
          //SIM 测试（一键测试WLAN、验收测试WLAN）
           /* simtaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            s.append("认证成功率：").append(task.simAuthSuccessRate).append("%");
            s.append("\n下线成功率：").append(task.simAuthSuccessRate).append("%"); //====================
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            simtaskLayout.addView(t);*/
            
          //segregate 测试（一键测试WLAN、验收测试WLAN）
            roamtaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            s.append("成功率：").append(task.userRoamSuccessRate).append("%");
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            roamtaskLayout.addView(t);
            
          //roam 测试（一键测试WLAN、验收测试WLAN）
            segregatetaskTitlteLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            s.append("成功率：").append(task.userIsolateSuccessRate).append("%");
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            segregatetaskLayout.addView(t);
        }
        
        if(task.selNetType == ConnectivityManager.TYPE_MOBILE){
        	rsnrtaskTitleLayout.setVisibility(VISIBLE);
        	snrtaskLayout.setVisibility(VISIBLE);
        	//snr 测试   (都有)
            s = new StringBuffer();
            s.append("SNR：").append(task.snr);
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            snrtaskLayout.addView(t); 
        } 
      //rssi 测试   (都有)
        s = new StringBuffer();
      
        if(task!=null && task.selNetType == ConnectivityManager.TYPE_MOBILE || task.selNetType == ConnectivityManager.TYPE_MOBILE_MMS)
        {
        	s.append("CI：").append(task.ci);
            s.append("\nLAC：").append(task.lac);
        	s.append("\n信号强度：").append("-"+task.rssi).append(" dBm");
        }
        else {
        	s.append("信号强度：").append(task.rssi).append(" dBm");
		}
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        rssitaskLayout.addView(t);
        showTaskNum();
    }
    private void showTaskNum() {
        int infoSize = ctx.getIntent().getIntExtra("info", 0);
        if (infoSize > 0) {
            DBManager db = new DBManager(ctx);
            List<TaskConfig> configs = db.getTask(task.apName, String.valueOf(task.id));
            db.release();
            StringBuffer s = new StringBuffer();
            s.append("已完成此热点下  ").append(configs.size()).append(" 项测试.");
            s.append("还剩 ").append(infoSize - configs.size()).append(" 项.");
            TextView tv = new TextView(ctx);
            tv.setText(s);
            tv.setTextSize(14);
            tv.setTextColor(Color.CYAN);
            taskNumLayout.addView(tv);
        }
    }
    public void showCameraDialog(final Activity ctx) { 
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx);  
        	builder.setTitle("拍照提示");   
        	builder.setMessage("是否进行测试现场拍照？");
        	builder.setCancelable(true);
     		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
     			public void onClick(DialogInterface dialog, int id) {
                	GlobalApp.who_to_CameraWidget = MessageWhat.TaskResult;
                   CameraWidget cw = new CameraWidget(ctx);
                   ctx.setContentView(cw);
     			}
     		}); 
     		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
             	public void onClick(DialogInterface dialog, int id) {
             		try {
     					Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
     					field.setAccessible(true);
     					field.set(dialog, true);
     				} catch (Exception e) {
     					e.printStackTrace();
     				}
             		dialog.cancel();
             	}
             });
     		wifiListDialog = builder.create();
            wifiListDialog.show();
		  
    }
	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}
	public Task dealWebAndPeapData(Task task){
		if(task==null || task.scanResult==null || task.scanResult.SSID==null || !task.scanResult.SSID.equals(WlanManager.SSID_CMCC)){
			task.webDelay = "-1";
			task.webOffSuccessRate="-1";
			task.webSuccessRate = "-1";
		} 
		if(task==null || task.scanResult==null || task.scanResult.SSID==null || !task.scanResult.SSID.equals(WlanManager.SSID_CMCC_AUTO)){
			task.peapAuthAvgTime = "-1";
			task.peapDelay="-1";
			task.peapOffSuccessRate = "-1";
			task.peapSuccessRate = "-1";
		}
		return task;
	}
}
